package com.qunar.wan.service;

import com.qunar.wan.common_api.model.Query;
import com.qunar.wan.common_api.serializer.RowBounds;
import com.qunar.wan.common_api.service.BaseService;
import com.qunar.wan.common_api.service.mapper.BaseMapper;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * 数据库公共类Dao类接口实现类
 * <p/>
 * User: cyoung Date: 11/25/13 Time: 11:20 AM
 * 
 * @param <T> 实体类
 * @param <E> 实体类对应Mapper
 */
@Service
public class BaseServiceImpl<T, E> implements BaseService<T, E>, Serializable {

    private static final long serialVersionUID = -8880164578630649070L;
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private Class<E> mapperClass;

    @Resource
    private SqlSession sqlSession;

    /**
     * 设置对应的MapperClass
     */
    public void setMapperClass() {
        this.mapperClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
    }

    @SuppressWarnings("unchecked")
    public BaseMapper<T> getBaseMapper() {
        return (BaseMapper<T>) this.getMapper();
    }

    /**
     * 得到对应的Mapper对象
     */
    public E getMapper() {
        if (mapperClass == null) {
            setMapperClass();
        }
        return sqlSession.getMapper(mapperClass);
    }

    @Override
    public List<T> selectByQuery(Query query) {
        return this.getBaseMapper().selectByQuery(query);
    }

    @Override
    public List<T> selectByQuery(Query Query, RowBounds rowBounds) {
        return this.getBaseMapper().selectByQuery(Query, rowBounds);
    }

    @Override
    public void deleteByPK(Object primaryKey) {
        this.getBaseMapper().deleteByPK(primaryKey);
    }

    @Override
    public void insertObj(T t) {
        this.getBaseMapper().insertObj(t);
    }

    @Override
    public int updateObj(T t) {
        return this.getBaseMapper().updateObj(t);
    }

    /**
     * 返回count
     * 
     * @param query
     * @return
     */
    public int selectCount(Query query) {
        return this.getBaseMapper().selectCount(query);
    }

}
